package com.tencent.org.service.impl;

import com.tencent.basic.service.impl.BaseServiceImpl;
import com.tencent.basic.util.BaiduAuditUtils;
import com.tencent.basic.util.MD5Utils;
import com.tencent.basic.util.StrUtils;
import com.tencent.org.domain.Employee;
import com.tencent.org.domain.Shop;
import com.tencent.org.domain.ShopAuditLog;
import com.tencent.org.dto.ShopDto;
import com.tencent.org.mapper.EmployeeMapper;
import com.tencent.org.mapper.ShopAuditLogMapper;
import com.tencent.org.mapper.ShopMapper;
import com.tencent.org.service.IShopService;
import com.tencent.user.domain.Logininfo;
import com.tencent.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * 实现类 ： 店铺 的 Service的 实现类
 * 控制事务 支持+只读  SUPPORTS - 如果其他bean调用这个方法,在其他bean中声明事务,那就用事务.如果其他bean没有声明事务,那就不用事务.
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
     * 店铺入驻
     * @param shop
     */
    @Override
    @Transactional
    public void settlement(Shop shop) {
        // ①校验
        //     校验空值 - 通过StringUtil(SpringFramework提供的)的方法isEmpty() - 只要有一个为空 就抛出业务异常
        if(StringUtils.isEmpty(shop.getName()) || StringUtils.isEmpty(shop.getTel()) ||
                StringUtils.isEmpty(shop.getAddress()) || StringUtils.isEmpty(shop.getName()) ||
                StringUtils.isEmpty(shop.getEmployee().getUsername()) || StringUtils.isEmpty(shop.getEmployee().getEmail()) ||
                StringUtils.isEmpty(shop.getEmployee().getPhone()) || StringUtils.isEmpty(shop.getEmployee().getPassword()))
        {
            throw new RuntimeException("数据不能为空"); // 接口e.getMassage可以接收到 并且返回给前端
        }
        //      校验密码 前端已经校验了 就不做了 - 要做的话 就在t_employee中加上一个字段(前端对应)

        //      校验店铺名称是否合规 调用我们封装好的百度智能云AI的工具类
        Boolean boo = BaiduAuditUtils.TextCensor(shop.getName());
        if (!boo) {
            throw new RuntimeException("店铺名称不合规！");
        }

        //      是否曾经入驻过 - 已入驻的不允许再次入驻
        Shop shopTemp = shopMapper.loadByMessage(shop); // 这个方法用传入的shop去对比数据库的数据
        if(shopTemp != null) { // 存在
            throw new RuntimeException("请勿重复入驻，若密码遗忘，请联系管理员");
        }

        // ②添加到数据库
        // 先添加店长 因为这样可以获取自增长的id 在添加店铺的时候 可以set进admin_id
        Employee employee = shop.getEmployee(); // 将传递过来的数据中的店长数据接收

        // 加密加盐
        String salt = StrUtils.getComplexRandomString(32);
        String md5Password = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Password);

        // 添加logininfo信息
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);

        // 获取logininfo的ID设置进employee中
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);

        // 添加店铺
        shop.setAdmin_id(employee.getId());
        shopMapper.save(shop);

        // 将店铺设置给店长的shop_id
        employee.setShop_id(shop.getId());
        employeeMapper.update(employee);
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        // 映射复制
        BeanUtils.copyProperties(employee, logininfo);
        // 设为管理员
        logininfo.setType(0);
        return logininfo;
    }

    /**
     * 通过待激活
     * @param log
     * @throws MessagingException
     */
    @Override
    @Transactional
    public void pass(ShopAuditLog log) throws MessagingException { // log里面包含了shopId和note
        // 1. 审核通过 修改状态为 待激活 =2 - 使用shopId获取到店铺 修改店铺的状态
        Shop shop = shopMapper.loadById(log.getShopId()); // 当前正在审核的店铺对象
        shop.setState(2);
        shopMapper.update(shop);

        // 2. 将审核信息添加到日志里
        log.setState(2);
        log.setAuditId(325L);
        shopAuditLogMapper.save(log);

        //3.发送邮件：审核通过邮件 - 叫他激活
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        //设置发送方
        helper.setFrom("1004370140@qq.com");
        //设置主题
        helper.setSubject("店铺激活邮件");
        //设置内容
        helper.setText("<h1>你的店铺已经注册!!!</h1>" +
                "<img src='123.207.27.208"+shop.getLogo()+"' >" +
                "<a href='http://localhost:8080/shop/active/"+shop.getId()+"'>点击该链接激活</a>",true);
        //设置收件人 先写死
        // Employee employee = employeeMapper.loadById(shop.getAdmin_id());
        //helper.setTo(employee.getEmail());
        helper.setTo("1004370140@qq.com");
        //发送
        javaMailSender.send(mimeMessage);

    }

    /**
     * 驳回
     * @param log
     * @throws MessagingException
     */
    @Override
    @Transactional
    public void reject(ShopAuditLog log) throws MessagingException {
        // 获取店铺
        Shop shop = shopMapper.loadById(log.getShopId());

        // 1. 添加审核日志到数据库
        log.setState(4);
        log.setAuditId(325L);
        shopAuditLogMapper.save(log);

        // 2. 发送邮件：驳回邮件 - 告诉他审核失败，重新入驻
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        // 设置发送方
        helper.setFrom("1004370140@qq.com");
        // 设置主题
        helper.setSubject("入驻失败邮件");
        // 设置内容
        helper.setText("<h1>入驻失败!!!</h1>" +
                "<a href='http://localhost:8081/#/register'>点击重新入驻</a>",true);
        // 设置收件人
        Employee employee = employeeMapper.loadById(shop.getAdmin_id());
        // helper.setTo(employee.getEmail());
        helper.setTo("1004370140@qq.com");
        // 发送
        javaMailSender.send(mimeMessage);

        // 3. 删除入驻信息
        // 删除管理员信息
        employeeMapper.remove(shop.getAdmin_id());
        // 删除店铺信息
        shopMapper.remove(shop.getId());

    }

    /**
     * 获取店铺状态 做店铺审核按钮的禁用功能
     * @return
     */
    @Override
    public List<ShopDto> getShopState() {
        return shopMapper.getShopState();

    }

    /**
     * 激活后修改店铺状态的
     * @param id
     */
    @Override
    public void shopActive(Long id) {
        Shop shop = shopMapper.loadById(id);
        shop.setState(3);
        shopMapper.update(shop);
    }
}
